package com.guigu.equipmentservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.common.utils.R;
import com.guigu.equipmentservice.dto.DetectionReportDto;
import com.guigu.equipmentservice.entity.DetectionReport;
import com.guigu.equipmentservice.entity.DetectionReportImage;
import com.guigu.equipmentservice.entity.Equipment;
import com.guigu.equipmentservice.entity.EquipmentImage;
import com.guigu.equipmentservice.service.DetectionReportImageService;
import com.guigu.equipmentservice.service.DetectionReportService;
import com.guigu.equipmentservice.service.EquipmentImageService;
import com.guigu.equipmentservice.service.EquipmentService;
import com.guigu.equipmentservice.vo.DetectionReportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * <p>
 * 检测报告表（存储设备检测的结果及结论） 前端控制器
 * </p>
 *
 * @author zcy
 * @since 2025-09-28
 */
@RestController
@RequestMapping("/equipmentservice/detectionReport")
public class DetectionReportController {

    @Autowired
    private DetectionReportService detectionReportService;
    @Autowired
    private DetectionReportImageService detectionReportImageService;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private EquipmentImageService equipmentImageService;


    @PostMapping("/queryDetectionListByVo/{pageNum}/{pageSize}")
    public R queryDetectionListByVo(@PathVariable("pageNum") Integer pageNum,
                                    @PathVariable("pageSize") Integer pageSize,
                                    @RequestBody DetectionReportVo vo) {
        return detectionReportService.queryDetectionListByVo(pageNum, pageSize, vo);
    }


    @GetMapping("/queryDetectionById/{id}")
    public R queryDetectionById(@PathVariable("id") Long id) {
        return detectionReportService.queryDetectionById(id);
    }
    @GetMapping("/queryDetectionByEquipmentId/{id}")
    public R queryDetectionByEquipmentId(@PathVariable("id") Long id) {
        return detectionReportService.queryDetectionListByEquipmentId(id);
    }

    @PutMapping("/updateDetection/{id}/{status}/{remark}")
    public R updateDetection(@PathVariable("id") Long id,
                             @PathVariable("status") Integer status,
                             @PathVariable("remark") String remark) {
        return detectionReportService.updateDetection(id, status, remark);
    }

    /**
     * 根据设备id查询检测报告
     */
    @GetMapping("/queryDetectionReportByEquipmentId/{id}")
    public DetectionReport queryDetectionReportByEquipmentId(@PathVariable("id") Long id) {
        return detectionReportService.queryDetectionReportByEquipmentId(id);
    }

    /**
     * 前台-查看设备的检测报告信息
     * */
    @GetMapping("/selectDetectionReportInfoPC/{equipmentId}")
    public R selectDetectionReportInfoPC(@PathVariable("equipmentId") Integer equipmentId) {

        QueryWrapper<DetectionReport> detectionReportQueryWrapper = new QueryWrapper<>();
        detectionReportQueryWrapper.eq("equipment_id",equipmentId);
        detectionReportQueryWrapper.eq("audit_status",1);

        DetectionReport detectionReport = detectionReportService.getOne(detectionReportQueryWrapper);

        if (detectionReport==null) {
            return R.ok().data("detectionReport", null);
        }

        //查询检测报告图片
        QueryWrapper<DetectionReportImage> detectionReportImageQueryWrapper = new QueryWrapper<>();
        detectionReportImageQueryWrapper.eq("report_id",detectionReport.getReportId());
        List<DetectionReportImage> detectionReportImages = detectionReportImageService.list(detectionReportImageQueryWrapper);

        detectionReport.setDetectionReportImageListPC(detectionReportImages);

        return  R.ok().data("detectionReport",detectionReport);
    }

    /**
     * 前台-查看设备的检测报告信息+查询设备和设备第一张图片
     * */
    @GetMapping("/selectDetectionReportInfoPC2/{equipmentId}")
    public R selectDetectionReportInfoPC2(@PathVariable("equipmentId") Integer equipmentId) {

        QueryWrapper<DetectionReport> detectionReportQueryWrapper = new QueryWrapper<>();
        detectionReportQueryWrapper.eq("equipment_id",equipmentId);
        detectionReportQueryWrapper.eq("audit_status",1);

        DetectionReport detectionReport = detectionReportService.getOne(detectionReportQueryWrapper);

        if (detectionReport==null) {
            return R.ok().data("detectionReport", null);
        }

        //查询设备
        Equipment equipment = equipmentService.getById(equipmentId);
        detectionReport.setEquipment(equipment);

        // 2. 查询设备的第一张图片（按ID排序取第一条，确保一致性）
        QueryWrapper<EquipmentImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("equipment_id", equipmentId)
                .orderByAsc("image_id") // 按图片ID升序（假设ID自增，保证顺序）
                .last("LIMIT 1"); // 只取第一条（MySQL语法）
        // 如果是Oracle/SQL Server，用queryWrapper.last("FETCH FIRST 1 ROWS ONLY")

        EquipmentImage firstImage = equipmentImageService.getOne(queryWrapper);
        if (firstImage != null && firstImage.getImageUrl() != null) {
            // 3. 设置设备的第一张图片URL
            equipment.setImageUrl(firstImage.getImageUrl());
        }

        //查询检测报告图片
        QueryWrapper<DetectionReportImage> detectionReportImageQueryWrapper = new QueryWrapper<>();
        detectionReportImageQueryWrapper.eq("report_id",detectionReport.getReportId());
        List<DetectionReportImage> detectionReportImages = detectionReportImageService.list(detectionReportImageQueryWrapper);

        detectionReport.setDetectionReportImageListPC(detectionReportImages);

        return  R.ok().data("detectionReport",detectionReport);
    }


    /**
     * 新增检测报告
     * @param detectionReportDto
     * @return
     */
    @PostMapping("/addDetectionReport")
    public R addDetectionReport(@RequestBody DetectionReportDto detectionReportDto) {
        return detectionReportService.addDetectionReport(detectionReportDto);
    }

    /**
     * 前台-点击查看检测报告的时候先判断数据库是否有成功的
     * */
    @GetMapping("/selectDetectionReportInfoSuccess/{equipmentId}")
    public R selectDetectionReportInfoSuccess(@PathVariable("equipmentId") Integer equipmentId) {

        QueryWrapper<DetectionReport> detectionReportQueryWrapper = new QueryWrapper<>();
        detectionReportQueryWrapper.eq("equipment_id", equipmentId);
        detectionReportQueryWrapper.eq("audit_status", 1);

        DetectionReport detectionReport = detectionReportService.getOne(detectionReportQueryWrapper);

        return  R.ok().data("detectionReport",detectionReport);
    }


    //查询业务员自己已评估的设备
    @GetMapping("/getBusinessmanEquipmentList/{businessmanId}")
    public R getBusinessmanEquipmentList(@PathVariable("businessmanId") Integer businessmanId){
        QueryWrapper<DetectionReport> wrapper = new QueryWrapper<>();
        wrapper.eq("businessman_id",businessmanId);
        wrapper.eq("audit_status",1).or().eq("audit_status",2).or();
        List<DetectionReport> detectionReport = detectionReportService.list(wrapper);
        //获取设备信息
        for (DetectionReport d : detectionReport) {
//            //检测报告表
//            QueryWrapper<DetectionReportImage> reportImageQueryWrapper = new QueryWrapper<>();
//            reportImageQueryWrapper.eq("report_id",d.getReportId());
//            List<DetectionReportImage> list = detectionReportImageService.list(reportImageQueryWrapper);
//            d.setDetectionReportImages( list);


            // 1. 查询设备信息（避免空指针）
            Integer equipmentId = Math.toIntExact(d.getEquipmentId());
            if (equipmentId == null) {
                continue; // 设备ID为空则跳过
            }
            Equipment equipment = equipmentService.getById(equipmentId);
            if (equipment == null) {
                continue; // 设备不存在则跳过
            }
            d.setEquipment(equipment);

            // 2. 查询设备的第一张图片（按ID排序取第一条，确保一致性）
            QueryWrapper<EquipmentImage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("equipment_id", equipmentId)
                    .orderByAsc("image_id") // 按图片ID升序（假设ID自增，保证顺序）
                    .last("LIMIT 1"); // 只取第一条（MySQL语法）
            // 如果是Oracle/SQL Server，用queryWrapper.last("FETCH FIRST 1 ROWS ONLY")

            EquipmentImage firstImage = equipmentImageService.getOne(queryWrapper);
            if (firstImage != null && firstImage.getImageUrl() != null) {
                // 3. 设置设备的第一张图片URL
                equipment.setImageUrl(firstImage.getImageUrl());
            }
        }

        return R.ok().data("list",detectionReport);
    }


    @PutMapping("/updateDetectionReport/{id}/{eid}")
    public Boolean updateDetectionReport(@PathVariable Integer id,@PathVariable Integer eid) {
        //1。先删除原检测报告
        //1.1根据设备id删除检测报告
        QueryWrapper<DetectionReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("report_id",id);
        detectionReportService.remove(queryWrapper);

        //修改设备是否检测字段
        //并修改设备状态为已检测
        Equipment equipment = equipmentService.getById(eid);
        equipment.setIsDetected(1);
        return equipmentService.updateById(equipment);
    }

    @GetMapping("/selectDetectionReportByEqIdAndAudit/{equipmentId}/{Audit}")
    public  DetectionReport selectDetectionReportByEqIdAndAudit(@PathVariable("equipmentId") Long equipmentId,@PathVariable("Audit") Integer audit) {
        LambdaQueryWrapper<DetectionReport> wrapper = new LambdaQueryWrapper<>();
        if (audit == null) return null;
        if (equipmentId == null) return null;
        wrapper.eq(DetectionReport::getEquipmentId,equipmentId);
        wrapper.eq(DetectionReport::getAuditStatus,audit);
        return detectionReportService.getOne(wrapper);

    }


}
